package com.dotndot.view.activity;

import java.lang.reflect.Type;
import java.util.Collection;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.Button;

import com.dotndot.MomApplication;
import com.dotndot.R;
import com.dotndot.controller.Server.ReceiveServerParam;
import com.dotndot.controller.Server.SendServerParam;
import com.dotndot.controller.network.resData.ResGson;
import com.dotndot.controller.network.resData.ResStory;
import com.dotndot.view.list.BasicListAdapter;
import com.dotndot.view.list.item.StoryItem;
import com.dotndot.view.widget.PullToRefreshListView;
import com.dotndot.view.widget.PullToRefreshListView.OnRefreshListener;
import com.google.gson.reflect.TypeToken;

public class Story extends BaseActivity
{
    private String STORY_PUBLIC_VIEW_TYPE = "public";
    private String STORY_FRIEND_VIEW_TYPE = "friend";
    private String STORY_PRIVATE_VIEW_TYPE = "private";
    
    private boolean loadingMore = true;
    private boolean viewPageEnd = false;
    private Button mAddBtn;
    private PullToRefreshListView storyListView;
    private BasicListAdapter storyListAdapter;
    private String storyViewType = STORY_PUBLIC_VIEW_TYPE;
    private View subStoryLayout, friendLayout, privateLayout;
    private int viewPage = 0;
    
    
    @Override
    protected void onCreate( Bundle savedInstanceState )
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.story);
        
        viewInit();
        loadStoryList(true);
        Log.e("==gslee==", "========================== Story = onCreate ==");
    }

    @Override
    public void viewInit()
    {
        mAddBtn = (Button) findViewById(R.id.story_add_btn);
        mAddBtn.setOnClickListener(this);
        
        storyListView = (PullToRefreshListView) findViewById(R.id.story_list);
        storyListView.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh() {
                Log.e("==gslee==", "==================== Story Refresh Listener = ");
                loadStoryList(true);
            }
        });        

        View footerView = ((LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.listfooter, null, false);
        storyListView.addFooterView(footerView);
        
        storyListAdapter = new BasicListAdapter(Story.this);
        storyListView.setAdapter(storyListAdapter);

        storyListView.setOnScrollListener(new OnScrollListener(){
            
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {}
            
            @Override
            public void onScroll(AbsListView view, int firstVisibleItem,
                    int visibleItemCount, int totalItemCount) {
                
                
                //what is the bottom iten that is visible
                int lastInScreen = firstVisibleItem + visibleItemCount;             
                
                //is the bottom item visible & not loading more already ? Load more !
                if((lastInScreen == totalItemCount) && !(loadingMore) && !(viewPageEnd)){                 
                    loadingMore = true;
                    loadStoryList(false);                    
                }
            }
        });        
    }

    @Override
    public void receiveServerMsg( Message msg )
    {
        String resJson = null;
        ResGson resGson = null;
        Type collectionType = null;
        ReceiveServerParam recvData = (ReceiveServerParam) msg.obj;
        
        switch( recvData.getAPI() )
        {
            case STORY_LIST_API:
                if(loadingMore == false){
                    storyListAdapter.clear();
                }
                loadingMore = false;
                resJson = (String) recvData.getData();
                collectionType = new TypeToken<Collection<ResStory>>(){}.getType();
                resGson = new ResGson(resJson, collectionType);
                if(resGson.message.equals("RET_STORY_GET_LIST_SUCCESS")){
                    viewPageEnd = false;
                    List<ResStory> storyList = (List<ResStory>) resGson.object;
                    if(storyList.size() != 10){
                        viewPageEnd = true; 
                    }
                    if(storyList == null){
                        
                    }else{
                        for(ResStory story : storyList){
                            if(story.isImage){                            
                                String imgPath = MomApplication.STORY_IMAGE_URL + story.index;
                                storyListAdapter.addItem(new StoryItem(story.nickname, story.email, imgPath, story.content));
                            }else{
                                storyListAdapter.addItem(new StoryItem(story.nickname, story.email, null, story.content));
                            }
                        }
                        storyListAdapter.notifyDataSetChanged();
                    }
//                    storyListView.onRefreshComplete();
                }else if(resGson.message.equals("RET_STORY_GET_LIST_END")){
                    viewPageEnd = true;
                }
                break;
        }
    }

    @Override
    public void onClick( View v )
    {
        switch( v.getId() )
        {
            case R.id.story_add_btn:
                Intent intent = new Intent(this, AddStory.class);
                startActivity(intent);
                break;        
        }
    }
    
    private void loadStoryList(boolean init)
    {
        if(init){
            viewPage = 0;
        }else{
            viewPage++;
        }
        SendServerParam param = new SendServerParam(REQUEST.STORY_LIST_API);
        param.put(STORYLIST.userIndex, momApp.getUserInfo().getUserIndex());
        param.put(STORYLIST.viewType, storyViewType);
        param.put(STORYLIST.viewPage, String.valueOf(viewPage));
        requestNetwork(param);
    }    
}
